package com.freight.user.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.file.service.FileService;

import com.freight.msg.entity.Message;
import com.freight.msg.entity.MessageSend;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import com.freight.user.dao.CompanyUserDao;
import com.freight.user.entity.CompanyLicense;
import com.freight.user.entity.CompanyUser;
import com.freight.user.mapper.CompanyVoMapper;
import com.freight.user.service.CompanyLicenseService;
import com.freight.user.service.CompanyUserService;
import com.freight.user.service.IdCardService;
import com.freight.user.util.UserDtoUtils;
import com.freight.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 公司用户表接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class CompanyUserServiceImpl implements CompanyUserService {

    @Autowired
    private CompanyUserDao companyUserDao;

    @Autowired
    private CompanyVoMapper companyVoMapper;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    IdCardService idCardService;

    @Autowired
    CompanyLicenseService companyLicenseService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private OperationLogService operationLogService;

    @Override
    public CompanyUserDao getRepository() {
        return companyUserDao;
    }


    @Override
    public HomePageStatisticsVo homePageStatistics() {

        User user = securityUtil.getCurrUser();
        HomePageStatisticsVo homePageStatisticsVo = companyVoMapper.homePageStatistics(user.getId());
        HomePageStatisticsVo hp= companyVoMapper.tobeEntrustedorder(user.getId());
        if (hp!=null&&hp.getTobeEntrustedorderNum()!=null){
            homePageStatisticsVo.setTobeEntrustedorderNum(hp.getTobeEntrustedorderNum());
        }else {
            homePageStatisticsVo.setTobeEntrustedorderNum(0);
        }
        return homePageStatisticsVo;
    }

    @Override
    public CommpanyInformationVo getCommpanyInformation(Long userId) {

        CommpanyInformationVo commpanyInformationVo=companyVoMapper.getCommpanyInformation(userId);

        return commpanyInformationVo;
    }







    @Override
    public String updatecompanyStatus(Long userId, Integer companyStatus,String reason) {
        securityUtil.getCurrUser();
        CompanyUser companyUser=findByUserId(userId);
        companyUser.setCompanyStatus(companyStatus);
        save(companyUser);
        String content = "" ;
        String logContent = "" ;
        if(companyStatus == 0){
            //审核未通过，发送消息通知原因
            Message message = new Message();
            message.setTitle("企业认证");
            content="您的提交的“企业认证”审核未通过，原因："+reason+"。";
            logContent="货主信息审核不通过。原因："+reason;

            message.setType("3");
            message.setTopicId("5");
            message.setContent(content);
            message.setUserId(userId);
            message=messageService.save(message);

            MessageSend messageSend=new MessageSend();
            messageSend.setUserId(userId);
            messageSend.setMessageId(message.getId());
            messageSend.setType("3");
            messageSendService.save(messageSend);
        }else {
            Message message = new Message();
            message.setTitle("企业认证");
            content="您的提交的“企业认证”已经通过审核啦！";
            logContent="货主信息审核通过";

            message.setType("3");
            message.setTopicId("5");
            message.setContent(content);
            message.setUserId(userId);
            message=messageService.save(message);

            MessageSend messageSend=new MessageSend();
            messageSend.setUserId(userId);
            messageSend.setMessageId(message.getId());
            messageSend.setType("3");
            messageSendService.save(messageSend);
        }
        //操作记录
        operationLogService.saveOperationLog(2,logContent,userId.toString());
        return "审核成功";
    }

    @Override
    public Page<CompanyUser> findByCondition(CompanyUser companyUser, SearchVo searchVo, Pageable pageable) {

        return companyUserDao.findAll(new Specification<CompanyUser>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<CompanyUser> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");

                List<Predicate> list = new ArrayList<>();

                // 创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

    @Override
    public CompanyUser findByUserId(Long userId) {
        return companyUserDao.findByUserId(userId);
    }

    @Override
    public Integer getCompanyState(Long userId) {
        User u = securityUtil.getCurrUser();
        userId = UserDtoUtils.getCurrentUserId(u, userId);
        CompanyUser cu = companyUserDao.findByUserId(userId);
        if (cu.getCompanyLicenseId() != null) {
            return CommonConstant.REGISTING;
        } else {
            return CommonConstant.REGIST;
        }
    }

    @Override
    public CompanyAllPicId getCompanyPicId(Long userId) {
        User u = securityUtil.getCurrUser();
        userId = UserDtoUtils.getCurrentUserId(u,userId);
        CompanyUser cu = companyUserDao.findByUserId(userId);
        Long lId = cu.getCompanyLicenseId();
        CompanyLicense companyLicense = companyLicenseService.get(lId);
        CompanyAllPicId companyAllPicId = new CompanyAllPicId();


        if (companyLicense != null) {
            companyAllPicId.setCompanyLicenseFileId(companyLicense.getCompanyLicenseFileId());
        }
        return companyAllPicId;

    }
}